package com.burst.reptile.modular.common;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ModelAttribute;

import com.burst.reptile.common.utils.SecurityUtils;
import com.burst.reptile.common.utils.ToolUtil;
import com.burst.reptile.framework.constant.ConstantFactory;
import com.burst.reptile.framework.security.service.TokenService;
import com.burst.reptile.modular.system.entity.SysUser;
import com.burst.reptile.modular.system.service.ISysUserService;
import com.burst.reptile.modular.zp.entity.ZpCity;
import com.burst.reptile.modular.zp.entity.ZpColumn;
import com.burst.reptile.modular.zp.service.IZpCityService;
import com.burst.reptile.modular.zp.service.IZpColumnService;

import lombok.RequiredArgsConstructor;

/**
 * 定义全局变量
 * @author wujin
 *
 * @date: 2020年6月22日 下午4:38:17
 */
@ControllerAdvice
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class GlobalController {
	
	private final TokenService tokenService;
	
	private final IZpCityService cityService;
	
	private final IZpColumnService columnService;
	
	private final ISysUserService userService;

	@ModelAttribute
    public void addAttributes(Model model) {
		String citySite = tokenService.getCitySite();
		ZpCity byId = cityService.getById(citySite);
		String cityname = "重庆";
		if(ToolUtil.isNotEmpty(byId)) {
			cityname = byId.getShortName();
		}
        //将网站配置信息添加到全局变量
        model.addAttribute("cityname", cityname);
        
        // 登录用户信息
        if(SecurityUtils.isLogin()) {
        	Long userId = SecurityUtils.getLoginUserId();
        	SysUser user = userService.getById(userId);
        	user.setFormatName(ConstantFactory.me().getFormatName(user.getFormatId()));
			model.addAttribute("user", user);
			model.addAttribute("phone", user.getPhonenumber().replaceAll("(\\d{3})\\d{4}(\\d{4})","$1****$2"));
        }
        
        // 栏目列表
		List<ZpColumn> columns = columnService.listAll();
		model.addAttribute("columns", columns);
    }
}
